// pages/shopcanvas/shopcanvas.js

const util = require('../../utils/util.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    cancasHidden: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    this.data = JSON.parse(options.data)
    let that = this
    // console.log(this.data)
    wx.getSystemInfo({
      success: function (res) {
        // console.log(res)
        that.data.windowWidth = res.windowWidth
        // that.drowImg()
        that.wxGetImgInfos()
        wx.showLoading({
          title: '图片生成中',
        })
      },
    })
  },

  wxGetImgInfos: function () {
    let that = this
    let data = {
      page: 'pages/restaurant/restaurant',
      scene: this.data.shopId
    }
    Promise.all([
      this.wxGetImgInfo(this.data.logoUrl),
      util.downloadACode(data)
    ]).then(res => {
      that.drawImg(res[0].path, res[1])
    })
  },

  wxGetImgInfo: function (src) {
    return new Promise(resolve => {
      wx.getImageInfo({
        src: src,
        success: function (res) {
          resolve(res)
        }
      })
    })

  },

  drawImg: function (logoUrl, acodeUrl) {
    let height = 550
    let that = this
    let canvasContext = wx.createCanvasContext("share-shop", this)

    canvasContext.setFillStyle("#F8F8F8")
    canvasContext.fillRect(0, 0, this.data.windowWidth, height)

    canvasContext.drawImage("../../imgs/backimg.jpg", 0, 0, this.data.windowWidth, 150)

    // 绘制圆角背板
    let x = this.data.windowWidth * 0.05
    let y = 90
    let w = this.data.windowWidth * 0.9
    let h = 180 + this.getTextHeight(this.data.location, 18, 6, 12) + this.getTextHeight(this.data.notice, 18, 6, 12)
    h = h > 260 ? h : 260
    let r = 6

    canvasContext.save()

    canvasContext.beginPath()
    canvasContext.setFillStyle('#ffffff')
    canvasContext.setLineWidth(1)
    canvasContext.moveTo(x + r, y)
    canvasContext.arcTo(x + w, y, x + w, y + h, r)
    canvasContext.arcTo(x + w, y + h, x, y + h, r)
    canvasContext.arcTo(x, y + h, x, y, r)
    canvasContext.arcTo(x, y, x + w, y, r)
    canvasContext.setShadow(0, 0, 10, '#C8C8C8')
    canvasContext.fill()
    canvasContext.closePath()
    canvasContext.restore()

    canvasContext.setFontSize(25)
    canvasContext.setFillStyle('#FFFFFF')
    canvasContext.setTextBaseline('top')
    canvasContext.setTextAlign('center')
    canvasContext.fillText(this.data.shopName, this.data.windowWidth / 2, 20 + 0.5)
    canvasContext.fillText(this.data.shopName, this.data.windowWidth / 2, 20 - 0.5)
    canvasContext.fillText(this.data.shopName, this.data.windowWidth / 2 + 0.5, 20)
    canvasContext.fillText(this.data.shopName, this.data.windowWidth / 2 - 0.5, 20)

    // 绘制圆形头像
    let head_w = 80
    let head_h = 80
    let head_x = (this.data.windowWidth - 80) / 2
    let head_y = 60

    canvasContext.save()
    canvasContext.beginPath()
    canvasContext.arc(head_w / 2 + head_x, head_h / 2 + head_y, head_w / 2, 0, Math.PI * 2, false)
    canvasContext.clip()
    canvasContext.drawImage(logoUrl, head_x, head_y, head_w, head_h)

    canvasContext.closePath()
    canvasContext.restore()

    canvasContext.setFontSize(12)
    canvasContext.setTextAlign('left')
    canvasContext.setFillStyle('#B0B0B0')

    let info_icon_x = this.data.windowWidth * 0.05 + 20
    let info_text_x = this.data.windowWidth * 0.05 + 60

    canvasContext.drawImage("../../imgs/delicious.png", info_icon_x, 140, 30, 30)
    canvasContext.fillText(this.data.shopStyle, info_text_x, 145)
    canvasContext.drawImage("../../imgs/time.png", info_icon_x, 180, 30, 30)
    canvasContext.fillText(`营业时间：${this.data.openTime}-${this.data.endTime}`, info_text_x, 185)
    canvasContext.drawImage("../../imgs/tel.png", info_icon_x, 220, 30, 30)
    canvasContext.setFontSize(15)
    canvasContext.setFillStyle('#FF9966')
    canvasContext.fillText(this.data.shopTel, info_text_x, 225)
    canvasContext.setFontSize(12)
    canvasContext.setFillStyle('#B0B0B0')
    canvasContext.drawImage("../../imgs/distance.png", info_icon_x, 260, 30, 30)
    this.textWrap(canvasContext, this.data.location, 18, info_text_x, 260, 6, 12)
    let locationHeight = this.getTextHeight(this.data.location, 18, 6, 12)
    locationHeight = locationHeight > 40 ? locationHeight : 40
    if (!this.data.notice.length == 0) {
      canvasContext.drawImage("../../imgs/notice.png", info_icon_x, 260 + locationHeight, 30, 30)
      this.textWrap(canvasContext, this.data.notice, 18, info_text_x, 265 + locationHeight, 6, 12)
    }

    let ma_h = 120
    let ma_w = 120
    let ma_x = (this.data.windowWidth - ma_h) / 2
    let ma_y = 380
    canvasContext.drawImage(acodeUrl, ma_x, ma_y, ma_w, ma_h)

    canvasContext.setTextAlign('center')
    let tip_y = ma_y + ma_h + 15
    canvasContext.fillText("长按识别小程序码查看详情", this.data.windowWidth / 2, tip_y)

    canvasContext.draw(true, function () {
      that.setData({
        cancasHidden: true
      })
      that.saveCanvasImg()
    })
  },

  textWrap: function (canvasContext, text, lineLength, x, y, lineHeight, fontSize) {
    let lineCount = Math.ceil(text.length / lineLength)
    for (let i = 0; i < lineCount; i++) {
      let start = i * lineLength
      let stop = text.length - i * lineLength > lineLength ? i * lineLength + lineLength : i * lineLength + text.length - i * lineLength
      let str = text.substring(start, stop)
      canvasContext.fillText(str, x, y + i * (fontSize + lineHeight))
    }
    
  },

  getTextHeight: function (text, lineLength, lineHeight, fontSize) {
    let lineCount = Math.ceil(text.length / lineLength)
    return lineCount * (fontSize + lineHeight)
  },

  saveCanvasImg: function () {
    let that = this
    wx.canvasToTempFilePath({
      canvasId: 'share-shop',
      success: function (res) {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function () {
            wx.hideLoading()
            wx.showToast({
              title: '保存成功',
              duration: 1000,
              success: function () {
                setTimeout(function () {
                  wx.redirectTo({
                    url: `../restaurant/restaurant?shop_id=${that.data.shopId}`,
                  })
                }, 1000)
              }
            })
          }
        })
      }
    }, this)
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})